import styled from 'styled-components';
import React, {
    useCallback,
    useDeferredValue,
    useEffect,
    useRef,
    useState,
    useTransition,
} from 'react';
import {Form, Input, Button, Space, Select, toast} from 'acud';
import SlowList from './SlowList';
import {createPortal} from 'react-dom';

const FormItem = Form.Item;

const Wrapper = styled.div`
    .content {
        width: 660px;
        display: flex;
        flex-direction: column;
        background: #f7f7f9;
        padding: 20px;
        padding-bottom: 0px;
    }

    .acud-input,
    .acud-select {
        width: 140px;
    }

    .acud-space-item {
        span {
            font-size: 12px;
        }
    }

    pre {
        background: #f7f7f9;
        padding: 10px;
        margin-top: 20px;
        border: 1px dashed #e8e8e8;
        whitespace: pre-wrap;
        :hover,
        :active {
            border: 1px dashed #2468f2;
        }
        :focus-visible {
            outline: none;
        }
    }
`;

const areas = [
    {label: 'Beijing', value: 'Beijing'},
    {label: 'Shanghai', value: 'Shanghai'},
    {label: 'IS_NULL', value: 'IS_NULL'},
    {label: 'IN', value: 'IN'},
];

const EditForm: React.FC<any> = (props) => {
    const [form] = Form.useForm();
    const [data, setData] = useState('');
    const editableRef = useRef({} as HTMLPreElement);

    const onFinish = (values: any) => {
        setData(JSON.stringify(values, null, 2));
    };

    const inputItem = (father: number, children: number) => {
        const value = form.getFieldValue([
            'properties',
            father,
            'constraints',
            children,
            'operator',
        ]);
        if (value === 'IS_NOT_NULL' || value === 'IS_NULL') {
            return null;
        }
        return (
            <FormItem
                name={[children, 'value']}
                rules={[{required: true, message: '请输入标签值'}]}
            >
                <Input placeholder="请输入值" />
            </FormItem>
        );
    };

    const handleBlur = async () => {
        const updatedContent = editableRef?.current?.innerText || '';
        try {
            const value = JSON.parse(updatedContent);
            await value;
            form.setFieldsValue(value);
            setData(updatedContent);
        } catch (error: any) {
            toast.error({
                message: error.message || '请输入正确的json格式',
                duration: 3,
            });
        }
    };

    // 会比较卡
    const [text, setText] = useState('');

    const [query, setQuery] = useState('');
    const [pedding, startTransition] = useTransition();

    const handleChange = useCallback((e: any) => {
        setText(e.target.value);
        startTransition(() => {
            setQuery(e.target.value);
        });
    }, []);

    const deferredText = useDeferredValue(text);

    useEffect(() => {
        console.log('---text, query->', text, query, deferredText);
    }, [deferredText, query, text]);

    // 优化
    return (
        <Wrapper>
            <Form form={form} onFinish={onFinish}>
                <Form.List name="properties">
                    {(fields, {add, remove}) => (
                        <>
                            {fields.map((field) => (
                                <Space key={field.key} align="baseline">
                                    <Form.List
                                        name={[field.name, 'constraints']}
                                    >
                                        {(
                                            testList,
                                            {add: addtest, remove: removetest}
                                        ) => (
                                            <div className="content">
                                                {testList.map((testList) => (
                                                    <FormItem
                                                        shouldUpdate
                                                        noStyle
                                                        key={testList.key}
                                                    >
                                                        {() => (
                                                            <Space align="baseline">
                                                                <span>
                                                                    标签健
                                                                </span>
                                                                <FormItem
                                                                    name={[
                                                                        testList.name,
                                                                        'key',
                                                                    ]}
                                                                    rules={[
                                                                        {
                                                                            required:
                                                                                true,
                                                                            message:
                                                                                '请输入标签健',
                                                                        },
                                                                    ]}
                                                                >
                                                                    <Input placeholder="请输入标签健" />
                                                                </FormItem>
                                                                <FormItem
                                                                    name={[
                                                                        testList.name,
                                                                        'operator',
                                                                    ]}
                                                                    initialValue="beijing"
                                                                >
                                                                    <Select
                                                                        options={
                                                                            areas
                                                                        }
                                                                    />
                                                                </FormItem>
                                                                <span>值</span>
                                                                {inputItem(
                                                                    field.name,
                                                                    testList.name
                                                                )}

                                                                <Button
                                                                    onClick={() =>
                                                                        removetest(
                                                                            testList.name
                                                                        )
                                                                    }
                                                                >
                                                                    删除
                                                                </Button>
                                                            </Space>
                                                        )}
                                                    </FormItem>
                                                ))}
                                                <FormItem>
                                                    <Button
                                                        onClick={() =>
                                                            addtest()
                                                        }
                                                    >
                                                        添加条件
                                                    </Button>
                                                </FormItem>
                                            </div>
                                        )}
                                    </Form.List>
                                    <Button onClick={() => remove(field.name)}>
                                        {' '}
                                        删除
                                    </Button>
                                </Space>
                            ))}
                            <FormItem style={{marginTop: 20}}>
                                <Button onClick={() => add()}>
                                    添加条件组
                                </Button>
                            </FormItem>
                        </>
                    )}
                </Form.List>

                <FormItem style={{marginTop: 20}}>
                    <Button type="primary" htmlType="submit">
                        Submit
                    </Button>
                </FormItem>
            </Form>
            <h2>数据展示</h2>
            <pre
                ref={editableRef}
                contentEditable
                suppressContentEditableWarning
                onBlur={handleBlur}
            >
                {data}
            </pre>
            <input value={text} onChange={handleChange} />
            <SlowList text={query} />
            {/* {createPortal(
                <p>这个子节点被放置在 document body 中。</p>,
                document.body
            )} */}
        </Wrapper>
    );
};

export default EditForm;
